<?php
class ZOrder {
	static public function OnlineIt($order_id, $pay_id, $money, $currency='CNY', $service='alipay', $bank='支付宝',$trade_no='',$mchid){ 
		list($_, $_, $quantity, $_) = explode('-', $pay_id);
		if (!$order_id || !$pay_id || $money <= 0 ) return false;
		$order = Table::Fetch('order', $order_id);
		$team = Table::Fetch('team', $order['team_id']);
		$user_id = abs(intval($order['user_id']));
		team_state($team); 

		if ( $order['state'] == 'unpay' ) {

			$table = new Table('pay');
			$table->id = $pay_id;
			$table->vid = $trade_no;
			$table->order_id = $order_id;
			$table->money = $money;
			$table->currency = $currency;
			$table->bank = $bank;
			$table->service = $service;
			$table->create_time = time();
			$ia = array('id','vid', 'order_id', 'money', 'currency', 'service', 'create_time', 'bank');
			if (Table::Fetch('pay', $pay_id) || ! $table->insert($ia)) {
			   	return false;
			}
			if(!empty($order['card_id']))
			{
				$up_sql = 'update card set consume="Y",team_id='.$order['team_id'].',order_id='.$order_id.'  where id = "'.$order['card_id'].'" ';
				DB::Query($up_sql);
			}
			
			
			
			
			//update user money; +money
			Table::UpdateCache('user', $user_id, array(
						'money' => array( "money + {$money}" ),
						));             
			$u = array(
					'user_id' => $user_id,
					'admin_id' => 0,
					'money' => $money,
					'direction' => 'income',
					'action' => 'paycharge',
					'detail_id' => $pay_id,
					'create_time' => time(),
				  );
			DB::Insert('flow', $u);
			$user = Table::FetchForce('user', $user_id);
            //print_r($user);exit;
			if ($user['money']<$order['origin']-$order['card']){
				return false;
			}

			if (in_array($team['state'], array('soldout')) ||  $team['end_time']<time()) {
				return false;
			}

			Table::UpdateCache('order', $order_id, array(
						'pay_id' => $pay_id,
						'money' => $money,
						'state' => 'pay',
						'trade_no' => $trade_no,
						'service' => $service,
						'quantity' => $quantity,
						'pay_time' => time(),
						));

			$order = Table::FetchForce('order', $order_id);
			$is_pintuan_success = false;
			if ( $order['state'] == 'pay' ) {
				if($order['is_pin'] == 1)
				{
					$pin_o_l = DB::GetTableRow('pin_order_list', array('order_id'=>$order_id));
					$pin_id = $pin_o_l['pin_id'];
					$pin_order_info = DB::GetTableRow('pin_order', array('id'=>$pin_id));
					
					$pin_order_list = DB::LimitQuery('pin_order_list',array(
						'condition' => array('pin_id'=>$pin_id),
						'order' => 'ORDER BY createtime ASC',
					));
					
					$tuanzhang_info = array();
					$i = 0;

					$need_count = 0;
					foreach($pin_order_list as $o_list)
					{
						$val = Table::Fetch('order', $o_list['order_id']);
						if($val['state'] == 'pay')
						{
							$need_count++;
						}
						if($i == 0)
						{
							$tmp_user = Table::Fetch('user', $val['user_id']);	
							$tuanzhang_info = $tmp_user;
						}
						$i++;
					}
					//如果是团长开团，那么更新拼团开始时间为现在，结束时间也更新。
					if($need_count == 1)
					{
						Table::UpdateCache('pin_order', $pin_id, array(
							'createtime' => time(),
							'endtime' => time()+86400*$team['pin_day'],
							));
					}
					
					
						
					if($need_count>=$pin_order_info['need_count'])
					{
						//插入红包订单表  $team  mchid  mchid $INI['system']['wwwprefix']
						if($team['bonus_price'] >= 1)
						{
							  $mch_billno = $mchid.date('Ymd').time();
							  $openid = $tuanzhang_info['open_id'];
							  $total_amount = $team['bonus_price'] * 100;
							  $sql ="insert into bonus_order(orderid,user_id,is_tuanz,pin_id,mch_billno,openid,total_amount,state,addtime,sendtime)  
									 values({$order_id},{$tuanzhang_info[id]},1,{$pin_id},'{$mch_billno}','{$openid}',{$total_amount},0,".time().",0)";
							  DB::query($sql);
						}
						
						if($team['bonus_tuan_price'] >= 1)
						{
							$i = 0;
							foreach($pin_order_list as $o_list)
							{
								$val = Table::Fetch('order', $o_list['order_id']);
								if($val['state'] == 'pay')
								{
									if($i >= 1)
									{
										$tmp_user = Table::Fetch('user', $val['user_id']);	
										
										 $mch_billno = $mchid.date('Ymd').time();
										  $openid = $tmp_user['open_id'];
										  $total_amount = $team['bonus_tuan_price'] * 100;
										  
										  
										  $sql ="insert into bonus_order(orderid,user_id,is_tuanz,pin_id,mch_billno,openid,total_amount,state,addtime,sendtime)  
												 values({$order_id},{$tmp_user[id]},2,{$pin_id},'{$mch_billno}','{$openid}',{$total_amount},0,".time().",0)";
										  DB::query($sql);
										 
									}
									$i++;
								}
							}
					
							 
						}
						
						Table::UpdateCache('pin_order', $pin_id, array(
							'state' => 1,
							'finish_time' => time(),
							));
						$is_pintuan_success = true;
					}
				}
				//TeamBuy Operation
				ZTeam::BuyOne($order);
				if($is_pintuan_success && $order['is_pin'] == 1)
				{
					do_pintuan_success_notify($pin_id);
				}
			}
		}
		return true;
	}

	static public function CashIt($order) {
		global $login_user_id;
		if (! $order['state']=='pay' ) return 0;

		//update order
		Table::UpdateCache('order', $order['id'], array(
					'state' => 'pay',
					'service' => 'cash',
					'admin_id' => $login_user_id,
					'money' => $order['origin'],
					'pay_time' => time(),
					));
		  /* cash flow */
		$order = Table::FetchForce('order', $order['id']);
                ZFlow::CreateFromStore($order['user_id'], $order['origin']);
		ZTeam::BuyOne($order);
	}

	static public function CreateFromCharge($money, $user_id, $time,$service) {
		if (!$money || !$user_id || !$time || !$service) return 0;
		$pay_id = "charge-{$user_id}-{$time}";
		$oarray = array(
				'user_id' => $user_id,
				'pay_id' => $pay_id,
				'service' => $service,
				'state' => 'pay',
				'money' => $money,
				'origin' => $money,
				'create_time' => $time,
			       );
		return DB::Insert('order', $oarray);
	}
}
?>
